package com.ruoyi.common.utils;

import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import jodd.io.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ResourcesHelper {

    protected static Log logger = LogFactory.getLog(ResourcesHelper.class);

    /**
     * 确保目录存在
     *
     * @param dir
     */
    public static void ensureExist(String dir) {
        try {
            FileUtil.mkdirs(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件是否存在
     *
     * @param path
     * @return
     */
    public static boolean exist(String path) {
        File file = new File(path);
        return file.exists();

    }

    /**
     * 从网络读取文件(本地做cache)
     *
     * @param uri
     * @param extensions
     * @return
     * @throws IOException
     */
    public static byte[] read(String uri, String extensions) throws IOException {

        if (StringUtils.isEmpty(uri)) {
            logger.debug("资源链接为空，不做下载. uri[" + uri + "]");
            return null;
        }

        String[] datas = uri.split("/");
        String fileName = datas[datas.length - 1];
        String md5 = fileName.substring(0, 32);

        String saveDir = RuoYiConfig.getCachePath() + "/" + md5.substring(0, 2) + "/";
        ensureExist(saveDir);

        String path = saveDir + md5 + "." + extensions + ".cache";

        if (exist(path)) {
            byte[] bytes = FileUtil.readBytes(path);
            String localMd5 = Md5Utils.md5(bytes);
            logger.debug("缓存文件存在. path[" + path + "], localMd5[" + localMd5 + "], md5[" + md5 + "]");
            if (StringUtils.equals(localMd5, md5)) {
                return bytes;
            } else {
                logger.debug("缓存文件MD5验证失败,需要重新下载资源. path[" + path + "], localMd5[" + localMd5 + "], md5[" + md5 + "]");
                FileUtil.delete(path);
            }
        }

        int tryCount = 0;

        while (tryCount < 5) {

            tryCount += 1;

            // 压缩包不存在则下压缩包
            logger.debug("开始下载文件. uri[" + uri + "], path[" + path + "]");
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Referer", "http://yingyu.youzhi.net/");
            // headers.put("Referer", "http://yingyu.youzhi.net/");
            if (HttpUtils.download(uri, path, headers)) {
                logger.debug("文件下载成功. uri[" + uri + "], path[" + path + "]");
                return FileUtil.readBytes(path);
            }

        }

        return null;

    }

    public static void main(String[] args) throws IOException {
        byte[] datas = read("http://yuwen.cdn.youzhi.net/kkcyw/bookcover/d990a84ac7a8e397b61fdf5b8bc5453e", "jpg");
        System.out.println(datas.length);
    }
}
